package xin.petstore.framework.web.img;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.List;
import java.util.Random;


public class ImageUtils {
	private static final int imageWidth = 290;// 整体图片的宽度
	private static final int imageHeight = 85;// 整体图片的高度
	private static final int widths = 70;// 小图片的宽度
	private static final int heights = 45;// 小图片的高度

	private static final String picPath = "C:\\Users\\Administrator\\Desktop\\pic";
	private static final String offset="\\";
	private static final String tail = ".jpg";
	public ImageUtils() {
		super();
	}

	/**
	 * 横向拼接一组（多张）图像
	 * 
	 * @param pics 将要拼接的图像
	 *
	 * @param type 图像写入格式
	 *
	 * @return
	 */
	public static ByteArrayInputStream mergeImages(List<byte[]> pics, String type) {
		try {

			int len = pics.size();
			if (len < 1) {
				System.out.println("pics len < 1");
				return null;
			}
			ByteArrayInputStream resizeImage = null;
			BufferedImage[] images = new BufferedImage[len];
			int[][] imageArrays = new int[len][];
			for (int i = 0; i < len; i++) {
				byte[] fileBytes = pics.get(i);
				InputStream fos = new ByteArrayInputStream(fileBytes);
				images[i] = ImageIO.read(fos);
				int width = images[i].getWidth();
				int height = images[i].getHeight();
				if (width !=widths || height != heights) {
					resizeImage = resizeImage(fileBytes, widths, heights, type);
					images[i] = ImageIO.read(resizeImage);
					width = images[i].getWidth();
					height = images[i].getHeight();
				}
				imageArrays[i] = new int[width * height];// 从图片中读取RGB
				imageArrays[i] = images[i].getRGB(0, 0, width, height, imageArrays[i], 0, width);
			}

			int dst_width = 0;
            int dst_height = images[0].getHeight();  
			for (int i = 0; i < images.length; i++) {
                dst_height = dst_height > images[i].getHeight() ? dst_height : images[i].getHeight();  
				dst_width += images[i].getWidth();
			}
			if (dst_height < 1) {
				System.out.println("dst_height < 1");
				return null;
			}
			/*
			 * 生成新图片
			 */
			BufferedImage ImageNew = new BufferedImage(dst_width, dst_height, BufferedImage.TYPE_INT_RGB);
			int width_i = 0;
			for (int i = 0; i < images.length; i++) {
				ImageNew.setRGB(width_i, 0, images[i].getWidth(), dst_height, imageArrays[i], 0, images[i].getWidth());
				width_i += images[i].getWidth();
			}

			ByteArrayOutputStream os = new ByteArrayOutputStream();
			ImageIO.write(ImageNew, type, os);
			os.flush();
			return new ByteArrayInputStream(os.toByteArray());
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 纵向拼接一组（多张）图像
	 * @param pics 将要拼接的图像数组
	 * @param type 写入图像类型
	 * @param dst_pic  写入图像路径
	 * @return
	 */
	public boolean joinImageListVertical(String[] pics, String type, String dst_pic) {
		try {
			int len = pics.length;
			if (len < 1) {
				System.out.println("pics len < 1");
				return false;
			}
			File[] src = new File[len];
			BufferedImage[] images = new BufferedImage[len];
			int[][] imageArrays = new int[len][];
			for (int i = 0; i < len; i++) {
				// System.out.println(i);
				src[i] = new File(pics[i]);
				images[i] = ImageIO.read(src[i]);
				int width = images[i].getWidth();
				int height = images[i].getHeight();
				imageArrays[i] = new int[width * height];// 从图片中读取RGB
				imageArrays[i] = images[i].getRGB(0, 0, width, height, imageArrays[i], 0, width);
			}

			int dst_height = 0;
			int dst_width = images[0].getWidth();
			for (int i = 0; i < images.length; i++) {
				dst_width = dst_width > images[i].getWidth() ? dst_width : images[i].getWidth();
				dst_height += images[i].getHeight();
			}
			// System.out.println(dst_width);
			// System.out.println(dst_height);
			if (dst_height < 1) {
				System.out.println("dst_height < 1");
				return false;
			}
			/*
			 * 生成新图片
			 */
			BufferedImage ImageNew = new BufferedImage(dst_width, dst_height, BufferedImage.TYPE_INT_RGB);
			int height_i = 0;
			for (int i = 0; i < images.length; i++) {
				ImageNew.setRGB(0, height_i, dst_width, images[i].getHeight(), imageArrays[i], 0, dst_width);
				height_i += images[i].getHeight();
			}
			File outFile = new File(dst_pic);
			ImageIO.write(ImageNew, type, outFile);// 写图片
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	* @Title: waterMarkImage 
	* @Description: TODO 添加水印
	* @param @param pics  图片地址集合
	* @param @param type  类型
	* @param @param ch    汉字
	* @param @return    
	* @return ByteArrayInputStream   
	* @throws 
	*/ 
	public static ByteArrayInputStream waterMarkImage(List<byte[]> pics, String type,String ch) {

		try {
			//设置白色背景
			BufferedImage backgrondImage = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
			Graphics back_g = backgrondImage.createGraphics();
			back_g.fillRect(0, 0, imageWidth, imageHeight);
			back_g.setColor(Color.BLACK);// 设置黑色字体,同样可以graphics.setColor(Color.black);
			back_g.drawString("请从下图中通过点击选择出：  ", 5, 20);
			back_g.setColor(new Color(246,231,153));
			back_g.drawLine(0, 26, 290, 26);//    画线

			//汉字验证图片
//			ByteArrayInputStream drawRandCode = drawRandCode(ch, type);
//			Image drawRandCodeImage = ImageIO.read(drawRandCode);
//			int widthWMIr = drawRandCodeImage.getWidth(null);
//			int heightWMIr = drawRandCodeImage.getHeight(null);
//			BufferedImage imageCode = new BufferedImage(widthWMIr, heightWMIr, BufferedImage.TYPE_INT_RGB);
//			Graphics gCode = imageCode.createGraphics();
//			gCode.drawImage(drawRandCodeImage, 0, 0, widthWMIr, heightWMIr, null);
			back_g.drawImage(MyKaptcha.createImage(ch), 170, 5, 80, 20, null);//需要修改的数据值
			
			//拼接的图像处理
			ByteArrayInputStream mergeImages = mergeImages(pics, type);
			Image waterMarkImage = ImageIO.read(mergeImages);
			int widthWMI = waterMarkImage.getWidth(null);
			int heightWMI = waterMarkImage.getHeight(null);
			BufferedImage image = new BufferedImage(widthWMI, heightWMI, BufferedImage.TYPE_INT_RGB);
			Graphics g = image.createGraphics();
			g.drawImage(waterMarkImage, 0, 0, widthWMI, heightWMI, null);
			int x = (int) (imageWidth * 0.02); // "0.5"小数越大，水印越向左移动。
			int y = (int) (imageHeight * 0.09); // "0.5"小数越大，水印越向上移动。
			back_g.drawImage(waterMarkImage, imageWidth - widthWMI - x, imageHeight - heightWMI - y, widthWMI, heightWMI, null);
			//---------------------------------------------------------------
			back_g.dispose();
//			try {
//				ImageIO.write(backgrondImage, type, new File("e:/images/uiuiui."+type));
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			ImageIO.write(backgrondImage, type, os);
			os.flush();
			return new ByteArrayInputStream(os.toByteArray());
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	* @Title: getRandColor 
	* @Description: TODO 给定范围获得随机颜色
	* @param @param fc
	* @param @param bc
	* @param @return    
	* @return Color   
	* @throws 
	*/ 
	public static Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}
	
	/**
	* @Title: drawRandCode 
	* @Description: TODO 汉字
	* @param     
	* @return void   
	* @throws 
	*/ 
	public static ByteArrayInputStream  drawRandCode(String ch,String type){
		int width = 60, height = 20;
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		// 获取图形上下文
		Graphics g = image.getGraphics();
		// 生成随机类
		Random random = new Random();
		// 设定背景色
		g.setColor(getRandColor(200, 250));
		g.fillRect(0, 0, width, height);
		// 随机产生155条干扰线，使图象中的认证码不易被其它程序探测到
		for (int i = 0; i < 155; i++) {
			g.setColor(getRandColor(160, 200));
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int xl = random.nextInt(12);
			int yl = random.nextInt(12);
			g.drawLine(x, y, x + xl, y + yl);
		}
		String[] array = ch.split("");
		for (int i=1;i<=array.length-1;i++){
			String rand=array[i];
//			int x = 5;
//			// 设置字体旋转角度
//			 int degree = new Random().nextInt() % 30;
//			// 正向角度
//			((Graphics2D) g).rotate(degree * Math.PI / 90, x, 18);
//			g.drawString(ch, x, 18);
//			// 反向角度
//			((Graphics2D) g).rotate(-degree * Math.PI / 90, x, 20);
			// 将认证码显示到图象中    调用函数出来的颜色相同，可能是因为种子太接近，所以只能直接生成 
			g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));  
			if (array.length==5) {
				g.drawString(rand,10*i-3,15);
			}else{
				g.drawString(rand,13*i,15);   
			}
		} 
//		g.setColor(new Color(0, 0, 102));
//		g.setFont(new Font(null, Font.PLAIN, 14));
//		g.drawString(ch, (width - 36)/2, 15);//36是汉字的长度值，需要用g.getFontMetrics().stringWidth(ch)获取。
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			ImageIO.write(image, type, os);
			os.flush();
			return new ByteArrayInputStream(os.toByteArray());
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		
	}
	
	/**
	 * @return 
	* @Title: tipForImages 
	* @Description: TODO 刷新高频率  提示图片
	* @param @param ch
	* @param @param type
	* @param @return    
	* @return ByteArrayInputStream   
	* @throws 
	*/ 
	public static ByteArrayInputStream   tipForImages(String str,String type){
		//设置白色背景
		BufferedImage backgrondImage = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
		Graphics back_g = backgrondImage.createGraphics();
		back_g.fillRect(0, 0, imageWidth, imageHeight);
		back_g.setColor(new Color(184,195,236));// 设置黑色字体,同样可以graphics.setColor(Color.black);
		back_g.setFont(new Font("宋体", Font.PLAIN, 15));//	Font font = new Font("宋体", Font.PLAIN, 15);
		back_g.drawString(str, 15, 60);
//		try {
//			ImageIO.write(backgrondImage, "jpg", new File("e:/images/tip."+"jpg"));
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			ImageIO.write(backgrondImage, type, os);
			os.flush();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return new ByteArrayInputStream(os.toByteArray());
		
	}
	
	
	
	 /**
     * 重置图形的边长大小
     * @param width
     * @param height
     * @throws IOException
     */
    public static ByteArrayInputStream resizeImage(byte[] bytes,int width,int height,String type) throws IOException{
    	ByteArrayOutputStream bs = new ByteArrayOutputStream();  
        try{
        	BufferedImage src = ImageIO.read(new ByteArrayInputStream(bytes));
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			Graphics graphics = tag.getGraphics();
			graphics.setColor(new Color(246,231,153));
			graphics.drawImage(src, 0, 0, width, height, null);
			graphics.drawRect(0, 0, width-1, height-1);
			ImageIO.write(tag, type,bs);
            bs.flush();
        }catch(Exception e){
            e.printStackTrace();
        }
//        finally{
//        	try {
//				bs.close();
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//        }
        return new ByteArrayInputStream(bs.toByteArray()); 
    }


	public static byte[] toByteArray(String filename) throws IOException {

		File f = new File(filename);
		if (!f.exists()) {
			throw new FileNotFoundException(filename);
		}

		ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
		BufferedInputStream in = null;
		try {
			in = new BufferedInputStream(new FileInputStream(f));
			int buf_size = 1024;
			byte[] buffer = new byte[buf_size];
			int len = 0;
			while (-1 != (len = in.read(buffer, 0, buf_size))) {
				bos.write(buffer, 0, len);
			}
			return bos.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			bos.close();
		}
	}
}